package com.pony.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.google.common.base.Strings;
import com.pony.MobileInterface.entity.ProductOrder;
import com.pony.MobileInterface.service.ProductOrderForMobileService;
import com.pony.domain.PayEntity;
import com.pony.enumeration.PayCode;
import com.pony.service.PayService;
import com.pony.service.ShoppingCartService;
import com.pony.util.AlipayUtil;
import com.pony.util.TimeUtil;
import com.pony.util.WxPayUtil;

import me.hao0.wepay.core.Wepay;
import me.hao0.wepay.exception.WepayException;
import me.hao0.wepay.model.pay.AppPayResponse;
import me.hao0.wepay.model.pay.PayRequest;

/**
 * 包含支付、支付查询、异步通知、退款申请、退款查询
 *
 * @author: qiaoyi
 * @edit:
 * @created:17/3/13
 */
@Controller
@RequestMapping(value = "/wxpay")
public class WxPayController {
    private static final Logger log = LoggerFactory.getLogger(WxPayController.class);

    @Autowired
    PayService payService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    ProductOrderForMobileService productOrderForMobileService;

    /**
     * 支付下单
     * https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=8_3
     *
     * @param request
     * @param response
     * @param phone       手机号
     * @param totalAmount 金额
     * @param outTradeNo  商品订单号
     * @return
     */
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject orderPay(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam(required = false)
                                       String phone,
                               String totalAmount,
                               String outTradeNo,
                               String body,
                               String subject) {
        log.info("PayController begin param phone={},totalAmount={},outTradeNo={},body={},subject={}", phone, totalAmount, outTradeNo, body, subject);
        JSONObject result = new JSONObject();
        if (Strings.isNullOrEmpty(phone)) {
            result.put("result", false);
            result.put("phone", phone);
            result.put("msg", PayCode.PHONE_NULL);
            return result;
        }

        if (Strings.isNullOrEmpty(outTradeNo)) {
            result.put("result", false);
            result.put("phone", phone);
            result.put("msg", PayCode.MECNUM);
            return result;
        }

        if (Strings.isNullOrEmpty(totalAmount)) {
            result.put("result", false);
            result.put("phone", phone);
            result.put("msg", PayCode.CRASH_INVALID);
            return result;
        }

        ProductOrder productOrder = productOrderForMobileService.
                getProductOrderByOrderId(Integer.parseInt(outTradeNo));

        if (productOrder == null) {
            result.put("result", false);
            result.put("phone", phone);
            result.put("msg", PayCode.ORDERID);
            return result;
        }
        log.info("productOrder={}", productOrder.getCost());

        double cost = Double.parseDouble(totalAmount);
        log.info("cost={}", cost);
//        if(productOrder.get)
        int test = Double.compare(cost, productOrder.getCost());
        log.info("test={}", test);
        if (test != 0) {
            result.put("result", false);
            result.put("phone", phone);
            result.put("msg", PayCode.CHECK_MONEY);//查询钱数不符合
            return result;
        }

        PayRequest payRequest = new PayRequest();
        payRequest.setBody(subject);
        payRequest.setOutTradeNo(outTradeNo);
        payRequest.setTotalFee(Integer.parseInt(totalAmount));
        payRequest.setDetail(body);
        payRequest.setNotifyUrl(WxPayUtil.getPayNotifyUrl());
        payRequest.setClientId(request.getRemoteAddr());
        payRequest.setTimeStart(TimeUtil.getCurrentTime("yyyyMMddHHmmss"));
        Wepay wepay = WxPayUtil.getWepay();
        
        try {
        	AppPayResponse payRespose = wepay.pay().appPay(payRequest);
            result.put("msg", "获取预支付成功");
            result.put("result", true);
            result.put("data", payRespose);
            return result;
        } catch (WepayException e) {
            log.info("orderPay exception={}", e);
        }
        return result;
    }

    @RequestMapping(value = "/receive_notify")
    @ResponseBody
    public String payCheck(HttpServletRequest request,
                           @RequestParam(required = false)
                                   String totalAmount,
                           String outTradeNo,
                           String body,
                           String subject
    ) throws AlipayApiException, UnsupportedEncodingException {
        JSONObject json = new JSONObject();
        log.info("cashNum={},outTradeNo={}",
                totalAmount, outTradeNo);
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        log.info("param={}", params);
        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        log.info("after param={}  ", params);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayUtil.ALIPAY_PUBLIC_KEY, AlipayUtil.CHARSET, AlipayUtil.SIGN_TYPE);
        log.info("signVerified={}", signVerified);
        if (signVerified) {
            // TODO 验签成功后
            //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
            return "success";
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
    }

}
